<?php
/*
 * @Descripttion: 
 * @version: 1.0
 * @Author: Sam
 * @Date: 2022-04-07 20:24:44
 * @LastEditors: Sam
 * @LastEditTime: 2022-06-02 18:36:30
 */
declare (strict_types=1);

namespace app\admin\controller;
use app\admin\model\User as UserModel;
use app\common\BaseController;
use hg\apidoc\annotation as Apidoc;
use think\Request;
use think\App;
use think\facade\Db;
use app\common\support\PHPExcelService;



/**
 * @Apidoc\Title("用户管理")
 **/
class Plugin extends BaseController
{

protected $system = []; // 系统信息
protected $install_sql; // 安装插件生成的sql
protected $install_sql_file; // 安装数据库脚本
protected $install_api_route_file; // 安装api路由脚本
protected $install_admin_route_file; // 安装admin路由脚本
protected $resource_url = '//game.vrupup.com/resources/0_frame_source/';
protected $module_list = []; // 模块目录
protected $module_installed = []; //已安装模块

 public function __construct(App $app = null){
        parent::__construct($app);
        $this->mg_module = input('mg_module','admin');
          // 禁止正式环境访问本模块
          if(strtolower(app()->env->get('SYSTEM')) == 'product') {
            die('非法请求');
        }
        // 异常错误报错级别, 禁止未定义变量错误的提示
        error_reporting(E_ERROR | E_PARSE);
        // 读取是否安装;
        $this->system['install'] = file_exists(app()->getRootPath().'database/install/lock/install.lock');
        // 赋值资源链接
        if($this->system['install']) {
            // $module_list         = json_decode(file_get_contents($app->getRootPath().'database/mg_module'), true);
            $module_installed    =  json_decode(file_get_contents($app->getRootPath().'database/module_installed'), true); //已安装模块
            $this->module_list   = $module_list;
            $this->module_installed = $module_installed;
        }
    }

    
    /**
     * @Apidoc\Title("列表")
     * @Apidoc\Url("/admin/plugin_index")
     * @Apidoc\Method("GET")
     * @Apidoc\Returned("data", type="array", desc="业务数据",replaceGlobal="true",
     *   @Apidoc\Returned("start",type="int",desc="起始位置"),
     *   @Apidoc\Returned("limit",type="int",desc="查询数量"),
     *   @Apidoc\Returned("data",type="array",desc="返回数据"),
     *   @Apidoc\Returned("total",type="array",desc="数据总量")
     * )
     */
    public function index(Request $request)
    {

        $list = [];
        $dir_list = folder_read(app()->getRootPath().'database/plugins/');
        foreach ($dir_list as $key => $item) {
            if($key == 'mg') continue;
            $readme = file_get_contents(app()->getRootPath().'database/plugins/'.$key.'/readme');
            $readme = explode("\n", $readme);
            $list[] = [
                'module'      => $key,
                'name'        => !empty($readme[0]) ? trim($readme[0]) : $key,
                'intro'       => !empty($readme[1]) ? trim($readme[1]) : '-',
                'update_time' => !empty($readme[2]) ? trim($readme[2]) : '-',
            ];
        }
        $module_installed = $this->module_installed;
       return $this->success('',compact('list','module_installed'));
    }

    /**
     * @Apidoc\Title("插件安装")
     * @Apidoc\Url("/admin/plugin_install")
     * @Apidoc\Method("post")
     * @Apidoc\Returned("data", type="array", desc="业务数据",replaceGlobal="true",
     *   @Apidoc\Returned("start",type="int",desc="起始位置"),
     *   @Apidoc\Returned("limit",type="int",desc="查询数量"),
     *   @Apidoc\Returned("data",type="array",desc="返回数据"),
     *   @Apidoc\Returned("total",type="array",desc="数据总量")
     * )
     */
    public function install(){
        $module = input('post.name');
        if(\in_array($module,$this->module_installed))    return $this->error('该模块已安装');
        Db::startTrans();
        try {
            $mg_module   = $this->mg_module;
            array_push($this->module_installed,$module);
            $app_path    = app()->getRootPath();
            $root_path   = $app_path.'database/plugins/'.$module.'/';
            $target_path = $app_path.'app/';
            $db_pre      = app()->env->get(SYSTEM.'.db_pre', '');
            $search      = ['__MODULE__', '__DB_PRE__', '__TIMESTAMP__'];
            $replace     = [$mg_module, $db_pre, time()];
            $files       = folder_read($root_path);
            $this->install_files($files, $root_path, $target_path, $search, $replace, $mg_module);
            // 建表
            $sql = $this->install_sql;
            if(!empty($sql)) {
                $sql_list = explode(';', $sql);
                foreach ($sql_list as $sql) {
                    $sql = trim($sql);
                    if(!empty($sql)) Db::execute($sql.';');
                }
            }
            // 安装api路由
            if(!empty($this->install_api_route_file)){
                $router_file_tpl = file_get_contents($this->install_api_route_file);
               
                $a = file_put_contents($target_path.'api/route/route.php', $router_file_tpl,FILE_APPEND);
                
            }
            // 安装admin路由
            if(!empty($this->install_admin_route_file)){
                $router_file_tpl = file_get_contents($this->install_admin_route_file);
                \file_put_contents($target_path.'admin/route/route.php', $router_file_tpl,FILE_APPEND);
            }
            if(!empty($this->install_sql_file)) {
                require_once $this->install_sql_file;
            }
            file_put_contents($app_path."/database/module_installed", json_encode($this->module_installed)); //写入已安装模块
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
           return $this->error($e->getMessage().$e->getFile());
        }
        return $this->success('安装成功');
    }


        /**
     * 安装包文件夹移动
     * @param array $files 文件列表
     * @param string $root_path 源目录
     * @param string $target_path 目标目录
     * @param array $search
     * @param array $replace
     * @param string $mg_module // 安装模块
     * @date 2020/8/6 21:53
     */
    private function install_files($files=[], $root_path='', $target_path='', $search=[], $replace=[], $mg_module='') {
        foreach ($files as $dir=>$file) {
            if(is_array($file)) {
                $path = $target_path.($dir == '__MODULE__' ? $mg_module.'/' : $dir.'/' );
                $this->install_files($file, $root_path.$dir.'/', $path, $search, $replace);
            }else {
                $this->install_file($root_path.$file, $target_path.$file, $search, $replace);
            }
        }
    }


        /**
     * 安装包文件移动
     * @param string $file 源文件地址
     * @param string $target_file 目标文件地址
     * @param array $search
     * @param array $replace
     * @date 2020/8/6 21:43
     */
    private function install_file($file='', $target_file='', $search=[], $replace=[]) {
        $content = str_replace($search, $replace, file_get_contents($file));
        // 递归创建目录
        folder_build(dirname($target_file));
        // 判断文件是否需要覆盖
        if(strpos($file, 'sql.sql') !== false) {
            $this->install_sql = $content;
            return ;
        }else if(strpos($file, 'readme') !== false) {
            return ;
        }else if(strpos($file, 'query.php') !== false) {
            $this->install_sql_file = $file;
            return ;
        }else if(strpos($file, 'route.tpl') !== false) {
            $this->install_api_route_file = $file;
            return ;
        }else if(strpos($file, 'adminRoute.tpl') !== false) {
            $this->install_admin_route_file = $file;
            return ;
        }
        // 备份原文件
        if(is_file($target_file) && file_get_contents($target_file) != $content) {
            file_put_contents($target_file.'_bak'.date('YmdHis'), file_get_contents($target_file));
        }
        file_put_contents($target_file, $content);
    }

}
